<?php
/**
 * Created by PhpStorm.
 * User: zyark
 * Date: 2017/8/25
 * Time: 16:37
 */

namespace Home\Logic;


use Admin\Logic\MoneyLogLogic;
use Common\Utils\Constants;
use Home\Model\Page;
use Think\Exception;
use Think\Log;

class RaceLogic
{
    /**
     * 获取赛事列表
     * @param $map
     * @param int $pagenum
     * @param int $pagesize
     * @return mixed
     */
    public function getRaceList($map,$pagenum=1,$pagesize=20){
        $startno = ($pagenum - 1) * $pagesize;
        $limit = $startno . ',' . $pagesize;//每页的数据数和内容$limit
        $map['is_delete'] = 0;
        $map['is_show'] = 1;
        $raceList = D('Race')->field('t_race.*')
            ->where($map)
            ->order('id desc')->limit($limit)
            ->select();
        $model = M();
        $model->startTrans();
        try {
            foreach ($raceList as $key => $value) {
                $status = $this->getStatus($value);
                if ($value['status'] != $status) {
                    $raceList[$key]['status'] = $status;
                    //修改状态
                    $model->table('t_race')->where(array('id' => $value['id']))->setField('status', $status);
                }
                $raceList[$key]['model_name'] = $value['model'] == 0 ? '1v1' : ($value['model'] == 1 ? '3v3' : '5v5');
            }
            $model->commit();
        }catch (Exception $e){
            Log::write($e->getMessage());
            $model->rollback();
        }
        $data['list'] = $raceList;
        $count = D('Race')->where($map)->count();
        $page = new Page($pagenum, $count, $pagesize);
        $page = (array)$page;//转换为数组
        $data['page'] = $page;
        return $data;
    }

    public function getRaceById($race_id){
        $race = D('Race')->where(array('id'=>$race_id))->find();
        $status = $this->getStatus($race);
        if ($race['status'] != $status) {
            $race['status'] = $status;
            //修改状态
            D('Race')->where(array('id' => $race['id']))->setField('status', $status);
        }
        $race['description'] = html_entity_decode($race['description']);
        $race['result'] = html_entity_decode($race['result']);
        $race['model_name'] = $race['model'] == 0 ? '1v1' : ($race['model'] == 1 ? '3v3' : '5v5');
        return $race;
    }

    //根据时间判断当前赛事状态
    private function getStatus($race){
        $now = time();
//        $race['status'] = 0;
        if($race['status'] == Constants::RACE_STATUS_GAME_END){
            return $race['status'];
        }else {
            if($race['game_start_time'] > $now){//赛事未开始
                if($race['apply_end_time'] > $now){//赛事报名未结束
                    if($race['apply_start_time'] > $now){//报名未开始
                        return Constants::RACE_STATUS_APPLY_WAIT;
                    }else{//报名中
                        return Constants::RACE_STATUS_APPLY_START;
                    }
                }else{//报名结束
                    return Constants::RACE_STATUS_GAME_START;
                }
            }else{
                //赛事进行中
                return Constants::RACE_STATUS_GAME_START;
            }
        }
    }

    /**
     * 报名
     * @param $user_id int 用户id
     * @param $race_id int 赛事id
     * @return int 0失败 1成功 2无法报名 3钻石不足 4报名人数已满
     */
    public function apply($user_id,$race_id){
        $race = D('Race')->where(array('id'=>$race_id))->find();
        $status = $this->getStatus($race);
        $money = $race['integral'];
        if($status != Constants::RACE_STATUS_APPLY_START){
            return 2;
        }
        $involved = D('ApplyLog')->where(array('race_id'=>$race_id))->count();
        if($race['people_number'] !=-1 && $involved >= $race['people_number']){
            return 4;
        }
        $user = D('User')->where(array('id'=>$user_id))->find();
        if($user['integral'] < $money){
            return 3;
        }
        $model = M();
        $model->startTrans();
        try{
            //扣除钻石
            $model->table('t_user')->where(array('id'=>$user_id))->setDec('integral',$money);
            //存储资金流动
            $remark = '使用钻石报名赛事('.$race['title'].')';
            $moneyLogLogic = new MoneyLogLogic();
            $moneyLogLogic->saveMoneyLog($money,
                $user['integral'] - $money,
                Constants::MONEY_SOURCE_APPLY,
                Constants::PUT_TYPE_OUT,
                $remark, $user_id,Constants::MONEY_TYPE_INTEGRAL, $model);
            //添加到报名记录
            $applyLogic = new ApplyLogic();
            $applyLogic->add($race_id,$user_id,$money,$model);
            $model->commit();
            return 1;
        }catch (Exception $e){
            Log::write($e->getMessage());
            $model->rollback();
            return 0;
        }
    }
}